package com.hk.userservice.service.impl;

import com.hk.model.WxUserRoleRelation;
import com.hk.userservice.mapper.WxUserRoleRelationMapper;
import com.hk.userservice.service.WxUserRoleRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/26 10:40
 * @Statement: 用户角色接口实现类
 */
@Slf4j
@Service
public class WxUserRoleRelationServiceImpl implements WxUserRoleRelationService {

    @Autowired
    private WxUserRoleRelationMapper userRoleRelationMapper;


    @Override
    public List<WxUserRoleRelation> findByAdminId(Integer id) {
        List<WxUserRoleRelation> userRoleRelationList = userRoleRelationMapper.findByAdminId(id);
        return userRoleRelationList;
    }


    @Override
    public List<WxUserRoleRelation> findAll(Integer page, Integer limit, WxUserRoleRelation wxUserRoleRelation) {
        return null;
    }

    @Override
    public int count(Integer page, Integer limit, WxUserRoleRelation wxUserRoleRelation) {
        return 0;
    }

    @Override
    public WxUserRoleRelation findById(Integer id) {
        return null;
    }

    /**
     * 1、现将有关当前管理员角色删除，然后再遍历添加
     * @param wxUserRoleRelation
     * @return
     */
    @Transactional
    @Override
    public int save(WxUserRoleRelation wxUserRoleRelation) {
//        1、先删除
        userRoleRelationMapper.deleteByAdminId(wxUserRoleRelation.getAdminId());
//        2、遍历添加
        String[] split = wxUserRoleRelation.getRoles().split(",");
        int count = 0;
        for (int i = 0; i < split.length; i++) {
            WxUserRoleRelation userRoleRelation = WxUserRoleRelation.builder().adminId(wxUserRoleRelation.getAdminId())
                    .roleId(Integer.parseInt(split[i])).build();
            int save = userRoleRelationMapper.save(userRoleRelation);
            count +=save;
        }
        if (count > 0) {
            log.error("管理员角色修改成功！");
        }
        return 0;
    }

    @Override
    public int update(WxUserRoleRelation wxUserRoleRelation) {
        return 0;
    }

    @Override
    public int delete(Integer id) {
        return 0;
    }

    @Override
    public int deleteByAdminId(Integer id) {
        int delete = userRoleRelationMapper.deleteByAdminId(id);
        return delete;
    }
}
